import { createRouter, createWebHistory, type NavigationGuardNext, type RouteLocationNormalized } from "vue-router"
import routes from "./routes"

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { useUserStore } from "@/store/user";
import type { UserInfoRes } from "@/serivce/modules/users/types";

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

interface metaData {
    title?: string,
    activeMenu?:string,
    showSide?:boolean,
    auth?:Array<string>
}

// routing to intercept
router.beforeEach(
    async (
        to: RouteLocationNormalized,
        from: RouteLocationNormalized,
        next: NavigationGuardNext
    ) => {
        NProgress.start()
        const userStore = useUserStore()
        const metaData:metaData = to.meta
        
        if(metaData.auth?.includes('ADMIN_USER') 
            && (userStore.getUserInfo as UserInfoRes).userType !=='ADMIN_USER' 
            && metaData.activeMenu == 'security') {
        
            to.fullPath = '/security/token-mange'
            next({name:'token-manage'})
        } else {
            next()
        }
        
        NProgress.done()
    }
)

router.afterEach(()=>NProgress.done())

export default router